package com.example.demo.conroller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import com.example.demo.pojo.Phone;

@Controller
public class HelloController {

	@RequestMapping("hello")
	@ResponseBody
	public String hello() {
		System.out.println("hello");
		return "hellosa";

	}

	@RequestMapping("hello2")
	@ResponseBody
	public String hello2(Phone[] phone) {
		for (Phone phone2 : phone) {
			long id = phone2.getId();
			System.out.println(id);
		}
		return "chenggogn";

	}

	@RequestMapping("/tologin")
	public String tologin(HttpServletRequest request, Map<String, Object> map, Model model) throws Exception {

		return "/login";

	}

	@RequestMapping("/login")
	public String login(HttpServletRequest request, Map<String, Object> map, Model model) throws Exception {

		String username = request.getParameter("username");
		String password = request.getParameter("password");
		// 1.获取subjec
		Subject subject = SecurityUtils.getSubject();

		System.out.println(username);
		System.out.println(password);
		// 2.分装数据
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		// 3.执行登录
		try {
			subject.login(token);
			return "redirect:/hello";
		} catch (UnknownAccountException e) {
			e.printStackTrace();
			model.addAttribute("msg", "用户名不存在");
			// return "redirect:/tologin";
		} catch (IncorrectCredentialsException e) {
			e.printStackTrace();
			model.addAttribute("msg", "密码错误");
		}
		// 此方法不处理登录成功,由shiro进行处理
		return "login";
	}

	@RequestMapping("/add")
	@ResponseBody
	public String add(HttpServletRequest request, Map<String, Object> map) throws Exception {

		// 此方法不处理登录成功,由shiro进行处理
		return "add";
	}

	@RequestMapping("index")
	public String index() {
		return "index";

	}

	@SuppressWarnings("rawtypes")
	public static void restTemplateMap() {
		RestTemplate restTemplate = new RestTemplate();
		Map map = restTemplate.getForObject("https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=ACCESS_TOKEN",
				Map.class);
		System.out.println(map.get("errmsg"));
	}

	public static void main(String[] args) {
		// restTemplateMap();
		
	}
}
